package com.shigen.demo.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.shigen.demo.Enum.HttpStatusCode;
import com.shigen.demo.config.ConfigProperty;
import com.shigen.demo.entity.UserInfo;
import com.shigen.demo.exception.BusinessException;
import com.shigen.demo.util.Common.Redis;
import com.shigen.demo.util.RedisUtil;
import com.shigen.demo.util.TokenUtil;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Service
public class UserService {

  @Resource
  private ConfigProperty configProperty;
  @Resource
  private TokenUtil tokenUtil;
  @Resource
  private RedisUtil redisUtil;

  public UserInfo getUserInfo() {
    ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (servletRequestAttributes != null) {
      HttpServletRequest request = servletRequestAttributes.getRequest();
      String token = request.getHeader("token");
      if (StrUtil.isNotEmpty(token)) {
        String key = Redis.TOKEN_PREFIX + tokenUtil.getRealToken(token);
        String userinfoString = redisUtil.get(key);
        if (StrUtil.isNotEmpty(userinfoString)) {
          return JSONObject.parseObject(userinfoString, UserInfo.class);
        }
      }
    }

    if (configProperty.isLoginDebugEnable()) {
      return new UserInfo().setUserId(configProperty.getId()).setUserName(configProperty.getName());
    } else {
      throw new BusinessException(HttpStatusCode.INTERNAL_SERVER_ERROR, "用户信息不存在");
    }
  }
}
